//
//  FindTravellingVC.m
//  AroundTheWorld
//
//  Created by IfelseGo on 16/5/24.
//  Copyright © 2016年 IfelseGo an. All rights reserved.
//

#import "FindTravellingVC.h"
#import "DataHandler.h"
#import "FindTravellingTableCell.h"
#import "FindTravellingModel.h"
#import "FindTravellingMenuTimes_rangeModel.h"


#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

static NSString *const findTravellReuse = @"findTravellReuse";
//static NSString *const enterDataReuse = @"enterDataReuse";

@interface FindTravellingVC ()

@property (nonatomic, strong) UITableView *myTabelView;
@property (nonatomic, strong) FindTravellingModel *datamodel;

@end

@implementation FindTravellingVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self getData];
    
    self.myTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 80, WIDTH, HEIGHT - 180) style:UITableViewStylePlain];
    self.myTabelView.backgroundColor = [UIColor whiteColor];
    //    self.myTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.myTabelView];
    self.myTabelView.showsVerticalScrollIndicator = NO;
 
    
    //成为代理人
    self.myTabelView.delegate = self;
    self.myTabelView.dataSource = self;
    
    //注册
    UINib *nib = [UINib nibWithNibName:@"FindTravellingTableCell" bundle:[NSBundle mainBundle]];
    [self.myTabelView registerNib:nib forCellReuseIdentifier:findTravellReuse];
    
    //monthMenu
     self.mothV = [[MonthMenuView alloc] initWithFrame:CGRectMake(0, - HEIGHT, WIDTH, HEIGHT - 80)];
    [self.view addSubview:self.mothV];
    [self.mothV showinView];
    // 设置菜单默认是关闭的
    self.isDisplayMenu = NO;
    
    //cityMenu
    self.cityV = [[CityMenuView alloc] initWithFrame:CGRectMake(0, - HEIGHT, WIDTH, HEIGHT - 80)];
    [self.view addSubview:self.cityV];
    [self.cityV showinView];
    // 设置菜单默认是关闭的
    self.isDisplayCity = NO;
    
    //选择月份按钮
    self.monthKey = @"不限";
    NSString *key = self.monthKey;
    self.monthButton = [self addLabelButton:@"出发时间 - " monthStr:key numberTag:1];
    [self.monthButton addTarget:self action:@selector(monthButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.monthButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
    
    //选择城市按钮
    self.cityKey = @"不限";
    NSString *cityKey = self.cityKey;
    self.cityButton = [self addLabelButton:@"目的地 - " monthStr:cityKey numberTag:2];
    [self.cityButton addTarget:self action:@selector(cityButtonAction:) forControlEvents:UIControlEventTouchUpInside];
   // [self.monthButton setTitleColor:[UIColor redColor] forState:UIControlStateSelected];

    //add分割线
    UIView *fgx = [[UIView alloc] initWithFrame:CGRectMake(WIDTH / 2 - 1, 20, 1, 65)];
    fgx.backgroundColor = [UIColor colorWithRed:230 / 255.0 green:230 / 255.0 blue:230 / 255.0 alpha:1.0];
    [self.view addSubview:fgx];
    
    //通知中心第一步: 注册一个通知
    //参数name:是消息通知的标识符, 只有发送者跟接收者的name参数一样, 接收者才能接收到发送者的消息.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changecolor:) name:@"changeColor" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(CityName:) name:@"CityName" object:nil];
    
    //刷新
    [self refreshTests];
    
    // Do any additional setup after loading the view.
}

//1.月份通知接受值
-(void)changecolor:(NSNotification *)noti
{
    self.mySearchArrayM = [NSMutableArray array];
    //月份搜索
    self.myFindModel = [noti object];
    self.monthKey = self.myFindModel.descriptionMenu;
    [self.monthButton setTitle:[NSString stringWithFormat:@"出发时间 -  %@",self.monthKey] forState:UIControlStateNormal];
    [self hideen:self.mothV];
    self.isDisplayMenu = NO;
    
    if ([self.cityKey isEqualToString:@"不限"]) {
        self.mySearchArrayM = [self seach:(self.myArrayM)];
        self.mySearchMonthArrayM = [self seach:(self.myArrayM)];
    }else
    {
        self.mySearchArrayM = [self seach:(self.mySearchCityArrayM)];
    }
    
    [self.myTabelView reloadData];
    
    [self seach:(self.myArrayM)];
    [self.myTabelView reloadData];
}
//月份搜索
- (NSMutableArray *)seach:(NSMutableArray *)arrayName
{
    NSMutableArray *array = [NSMutableArray array];
    NSInteger searchStartTime = self.myFindModel.start_time.intValue;
    NSInteger searchEndTime = self.myFindModel.end_time.intValue;
    //判断:开始时间大于月末, 结束时间小于月初 不是搜索范围
    for (FindTravellingModel *model in arrayName) {
        if (model.start_time.intValue > searchEndTime) {
            continue;
        }else if (model.end_time.intValue < searchStartTime) {
            continue;
        }else
        {
            [array addObject:model];
        }
    }
    return array;
}

//2.目的地通知接受值
-(void)CityName:(NSNotification *)noti
{
    self.mySearchArrayM = [NSMutableArray array];
    //目的地获取
    self.myFindCityModel = [noti object];
    self.cityKey = self.myFindCityModel.place_name;
    [self.cityButton setTitle:[NSString stringWithFormat:@"目的地 -  %@",self.cityKey] forState:UIControlStateNormal];
    [self hideen:self.cityV];
    self.isDisplayCity = NO;
    if ([self.monthKey isEqualToString:@"不限"]) {
       self.mySearchArrayM = [self seachCity:(self.myArrayM)];
       self.mySearchCityArrayM = [self seachCity:(self.myArrayM)];
    }else
    {
       self.mySearchArrayM = [self seachCity:(self.mySearchMonthArrayM)];
    }
    
    [self.myTabelView reloadData];
}
//国家搜索
- (NSMutableArray *)seachCity:(NSMutableArray *)arrayName
{
    NSMutableArray *array = [NSMutableArray array];
    for (FindTravellingModel *model in arrayName) {
        if (([model.citys_str rangeOfString:self.cityKey].location != NSNotFound) ||([model.title rangeOfString:self.cityKey].location != NSNotFound)) {
            [array addObject:model];
        }
    }
    return array;
}


//data
-(void)getData{
    self.myArrayM = [NSMutableArray array];
    DataHandler *handler1 = [[DataHandler alloc] init];
    [handler1 getCommunityFindTravellBase:1 SucceedHandler: ^(id result) {
        self.myArrayM = [NSMutableArray arrayWithArray:result];
        [self.myTabelView reloadData];
    } failedHandler:^(NSError *error) {
    }];
}
//添加按钮方法
- (UIButton *)addLabelButton:(NSString *)buttnTitle monthStr:(NSString *)monthStr numberTag:(NSInteger )num
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//    button.backgroundColor = [UIColor whiteColor];
    button.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff,0xCFCFCF);

    button.frame = CGRectMake(0 + WIDTH / 2 * (num - 1), 20, WIDTH / 2, 60);
    
    [button setTitle:[NSString stringWithFormat:@"%@ %@",buttnTitle, monthStr] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:15];
    button.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:button];
    return button;
}
//按钮高亮
- (void)updateButton:(UIButton *)button selected:(BOOL)selected
{
    UIColor *color = nil;
    if (selected) {
        //button 绿色
        color = [UIColor colorWithRed:53 / 255.0 green:176 /255.0 blue:131 / 255.0 alpha:1.0];
    }else {
        //button 灰色
        color = [UIColor grayColor];
    }
    [button setTitleColor:color forState:UIControlStateNormal];
    [button setTitleColor:color forState:UIControlStateHighlighted];
}

//出发时间选择
-(void)monthButtonAction:(UIButton *)button
{
    if (self.isDisplayCity == YES) {
        [self hideen:self.cityV];
        self.isDisplayCity = NO;
        [self show:self.mothV];
        self.isDisplayMenu = YES;
    }else if (self.isDisplayMenu == NO) {
        [self show:self.mothV];
        self.isDisplayMenu = YES;
    }else
    {
        [self hideen:self.mothV];
        self.isDisplayMenu = NO;
    }
}
//目的地选择
-(void)cityButtonAction:(UIButton *)button
{
    if (self.isDisplayMenu == YES) {
        [self hideen:self.mothV];
        self.isDisplayMenu = NO;
        [self show:self.cityV];
        self.isDisplayCity = YES;
    }else if (self.isDisplayCity == NO) {
        [self show:self.cityV];
        self.isDisplayCity = YES;
    }else
    {
        [self hideen:self.cityV];
        self.isDisplayCity = NO;
    }
}

#pragma mark -- 动画展开
-(void)show:(UIView *)view
{
    if (view == self.cityV) {
        [self updateButton:self.cityButton selected:YES];
    }else {
        [self updateButton:self.monthButton selected:YES];
    }
    [UIView animateWithDuration:0.2 animations:^{
        view.frame = CGRectMake(0, 80, WIDTH, HEIGHT - 80);
    }];
}
-(void)hideen:(UIView *)view
{
    [self updateButton:self.monthButton selected:NO];
    [self updateButton:self.cityButton selected:NO];
    [UIView animateWithDuration:0.2 animations:^{
        view.frame = CGRectMake(0, - HEIGHT - 100, WIDTH, HEIGHT - 80);

    }];
}


//cell高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
      return 155;
}

//cell数
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (![self.monthKey isEqualToString:@"不限"]) {
        return self.mySearchArrayM.count;
    }else if(![self.cityKey isEqualToString:@"不限"])
    {
        return self.mySearchArrayM.count;
    }else
    {
      return self.myArrayM.count;
    }
}

//建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (![self.monthKey isEqualToString:@"不限"]) {
        FindTravellingTableCell *cell = [tableView dequeueReusableCellWithIdentifier:findTravellReuse];
        FindTravellingModel *model = [self.mySearchArrayM objectAtIndex:indexPath.row];
        cell.myModel = model;
        return cell;
    }
    if (![self.cityKey isEqualToString:@"不限"]) {
        FindTravellingTableCell *cell = [tableView dequeueReusableCellWithIdentifier:findTravellReuse];
        FindTravellingModel *model = [self.mySearchArrayM objectAtIndex:indexPath.row];
        cell.myModel = model;
        return cell;
    }

    FindTravellingTableCell *cell = [tableView dequeueReusableCellWithIdentifier:findTravellReuse];
    FindTravellingModel *model = [self.myArrayM objectAtIndex:indexPath.row];
    cell.myModel = model;
    return cell;
}

//下拉刷新
- (void)refreshTests
{
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];

}

#pragma mark --下拉刷新
- (void)addHeader
{
    __block FindTravellingVC *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTabelView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
    }];
    
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTabelView headerBeginRefreshing];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    __block FindTravellingVC *vc = self;
    // 添加上拉刷新尾部控件
    [self.myTabelView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage ++;
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
         if (vc.nextPage < 50) {
            [vc showAlert:[NSString stringWithFormat:@"刷新到第%ld页",vc.nextPage]];
        }else
        {
            [vc showAlert:@"已经到底部,没有可加载数据!"];
        }
    }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
    DataHandler *handler = [[DataHandler alloc] init];
    [handler getCommunityFindTravellBase:nextCursor SucceedHandler: ^(id result) {
        if (self.isUpLoading == NO) {
            [self.myArrayM removeAllObjects];
        }
        
//        NSLog(@"=================1=======%ld",nextCursor);
        
        NSMutableArray *arrayTemp = [NSMutableArray arrayWithArray:result];
        for (FindTravellingModel *model in arrayTemp) {
            [self.myArrayM addObject:model];
        }
        [self.myTabelView footerEndRefreshing];
        [self.myTabelView headerEndRefreshing];
        [self.myTabelView reloadData];
    } failedHandler:^(NSError *error) {
    }];
}

//刷新后显示对话框
- (void)timerFireMethod:(NSTimer*)theTimer  //弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}

- (void)showAlert:(NSString *) _message{   //时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}



//点击方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    

}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
